package com.lqk.demo.atomic.atomicinteger;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;

/**
 * @author lqk
 * @date 2021/12/30 14:54
 */
public class updateAndGetPrinciple {
    public static void main(String[] args) {
        AtomicInteger i = new AtomicInteger(5);
        int i1 = updateAnGet(i, p -> p / 2);
        System.out.println(i1);
    }

    private static int updateAnGet(AtomicInteger i, IntUnaryOperator operator){
        while (true) {
            int prev = i.get();
            int next = operator.applyAsInt(prev);
            if (i.compareAndSet(prev,next)){
                return next;
            }
        }
    }
}
